package com.ly.aicode.core.saver;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.ly.aicode.model.enums.CodeGenTypeEnum;

import java.io.File;
import java.nio.charset.StandardCharsets;

/**
 * @author luyi
 * @date 2025/11/9 0:04
 */
public abstract class CodeFileSaveTemplate<T> {
    protected static final String BASE_PATH = System.getProperty("user.dir")+"/temp/code_output";

    public final File saveCode(T result) {
        //校验参数
        this.validate(result);
        //构造唯一目录路径
        String dirPath = buildUniqueDir();
        //写入文件
        this.saveFile(result, dirPath);
        //返回文件
        return new File(dirPath);
    }

    protected void validate(T result) {
        if (ObjUtil.isEmpty(result)) throw new RuntimeException("result不能为空");
    }

    //构造唯一目录路径
    private String buildUniqueDir() {
        String bizType = this.genTypeEnum().getValue();
        String fileName = StrUtil.format("{}_{}", bizType, IdUtil.getSnowflakeNextIdStr());
        String dirPath= BASE_PATH + File.separator + fileName;
        FileUtil.mkdir(dirPath);
        return dirPath;
    }

    //写入文件
    protected static void writeToFile(String content, String fileName, String dir) {
        String path = dir + File.separator + fileName;
        FileUtil.writeString(content,path, StandardCharsets.UTF_8);
    }


    protected abstract CodeGenTypeEnum genTypeEnum();

    protected abstract void saveFile(T result, String dirPath);

}
